package timing.ukulele.user.receiver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import timing.ukulele.common.dictionary.ThirdPartyTypeEnum;
import timing.ukulele.user.dictionary.WxMpMessageTemplateEnum;
import timing.ukulele.user.persistent.SysThirdPartyUser;
import timing.ukulele.user.service.SysThirdPartyUserService;
import timing.ukulele.user.util.WeiXinMpUtil;
import timing.ukulele.user.util.WeixinMessageUtil;

import java.util.List;
import java.util.Map;

import static timing.ukulele.user.config.TopicConfig.PASSWORD_ROUTING;

/**
 * 初始密码监听消息
 */
@Component
@Slf4j
public class PasswordMessageReceiver {
    private final WeixinMessageUtil messageUtil;
    private final SysThirdPartyUserService userService;

    public PasswordMessageReceiver(WeixinMessageUtil messageUtil, SysThirdPartyUserService userService) {
        this.messageUtil = messageUtil;
        this.userService = userService;
    }

    @RabbitHandler
    @RabbitListener(queues = PASSWORD_ROUTING)
    public void sendPasswordMessage(Map<String, Object> message) {
        if (CollectionUtils.isEmpty(message))
            return;
        Long id = null;
        if (message.containsKey("id"))
            id = (Long) message.get("id");
        if (id == null)
            return;
        List<SysThirdPartyUser> list = userService.lambdaQuery()
                .eq(SysThirdPartyUser::getPlatSource, ThirdPartyTypeEnum.WX_MP.getValue()).eq(SysThirdPartyUser::getUserId, id).list();
        if (CollectionUtils.isEmpty(list))
            return;
        String account = (String) message.get("account");
        String password = (String) message.get("password");
        String template = WeiXinMpUtil.getContentData(WxMpMessageTemplateEnum.REGISTRY_SUCCESS_MESSAGE.getPath());
        String messageBody = String.format(template, "您的账号注册成功", "https://www.yigongyun.cloud/", account, password, "请尽快修改该初始密码");
        messageUtil.sendMpMessage(WxMpMessageTemplateEnum.REGISTRY_SUCCESS_MESSAGE.getTemplateId(), list.get(0).getPlatId(), "pages/navigator/user/index", messageBody);
    }
}
